/**
 * 筹码选择页面的逻辑
 */

// 封盘时，将所有投注按钮置灰
var fengpan = false;
function on_fengpan() {
    if (fengpan) return;
    fengpan = true;
    do_fengpan();
}

function do_fengpan() {
    if (!fengpan) return;
    reset_counter();
    $("input[name='counter-input']").attr("disabled", "disabled");
    $("input[name='counter-input']").val("封盘");
}

// 开盘了
function on_kaipan() {
    if (!fengpan) return;
    fengpan = false;
    $("input[name='counter-input']").removeAttr("disabled");
    $("input[name='counter-input']").val('');
}

// 当前是否允许下注
var _enableBet = true;
Classify.query("settings", "bet_enable", false, "1", function(v) {
    _enableBet = v == '1';
});

// 添加一个下注项
function add_bet_item(key, title, container, hideTitle) {
    hideTitle = hideTitle === undefined ? false : hideTitle;
    var t = '<td class="name" value="__v__">__title__</td> ' +
            '<td class="odds" value="__v__"><span class="c-txt3 rate">__rate__</span></td> ' +
            '<td class="amount" value="__v__"><input type="text" name="counter-input"></td>';
    if (hideTitle)
        t = 
            '<td class="odds" value="__v__"><span class="c-txt3 rate">__rate__</span></td> ' +
            '<td class="amount" value="__v__"><input type="text" name="counter-input"></td>';

    // 取得赔率
    if (key.indexOf(":") > -1)
        key = key.split(":")[0];
    var rate = gameRule.map[key] ? gameRule.map[key].rate : "";
    t = t.replace(/__rate__/, rate);
    t = t.replace(/__title__/, title);
    t = t.replace(/__v__/g, key);
    container.append(t);
}

// 保证key不变
function add_bet_item2(key, title, container) {
    var t = '<td class="name" value="__v__">__title__</td> ' +
            '<td class="odds" value="__v__"><span class="c-txt3 rate">__rate__</span></td> ' +
            '<td class="amount" value="__v__"><input type="text" name="counter-input"></td>';
    var k = key;
    if (key.indexOf(":") > -1)
        key = key.split(":")[0];
    var rate = gameRule.map[key] ? gameRule.map[key].rate : "";

    t = t.replace(/__rate__/, rate);
    t = t.replace(/__title__/, title);
    t = t.replace(/__v__/g, k);
    container.append(t);
}

// 刷新赔率信息
function refresh_bet_items() {
    var arr = $("input[name='counter-input']");
    for (var i = 0; i < arr.length; i++) {
        var e = $(arr[i]);
        var key = e.parent().attr("value");
        if (key.startsWith('一:')) key = '一';
        if (key.startsWith('二:')) key = '二';
        if (key.startsWith('三:')) key = '三';
        if (key.startsWith('四:')) key = '四';
        if (key.startsWith('五:')) key = '五';
        if (key.startsWith('六:')) key = '六';
        if (key.startsWith('七:')) key = '七';
        if (key.startsWith('八:')) key = '八';
        if (key.startsWith('正:')) key = '正';
        if (key.startsWith('任1:')) key = '任1';
        var rate = gameRule.map[key] ? gameRule.map[key].rate : "";
        e.parent().parent().find("td[value='__v__'] .rate".replace(/__v__/, key)).html(rate);
    }

    var arr = $(".special-rate");
    for (var i = 0; i < arr.length; i++) {
        var e = $(arr[i]);
        var key = e.attr("key");
        var rate = gameRule.map[key] ? gameRule.map[key].rate : "";
        e.html(rate);
    }
}

// 扫描下所有的筹码录入框，并同步之
function scan_counter_confirm() {
    var input1 = $("#bet_money1"), input2 = $("#bet_money2");
    input1.on("input", function() {
        var v = input1.val();
        input2.val(v);
        get_selected_inputs().forEach(function(i) {
            i.val(v);
        });

        // 保存此数据
        try {
            if (localStorage) localStorage.setItem("com.cp-zy-counter", v);
        }
        catch(e) {
            console.error(e);
        }
    });
    input2.on("input", function() {
        var v = input2.val();
        input1.val(v);
        get_selected_inputs().forEach(function(i) {
            i.val(v);
        });

        // 保存此数据
        try {
            if (localStorage) localStorage.setItem("com.cp-zy-counter", v);
        }
        catch(e) {
            console.error(e);
        }
    });

    // 读取保存的数据
    var curr = 0;
    try {
        if (localStorage) {
            var v = localStorage.getItem("com.cp-zy-counter");
            if (v) curr = parseInt(v);
        }
    }
    catch(e) {
        console.error(e);
    }

    input1.val(curr || '');
    input2.val(curr || '');

    // 确定按钮的处理
    var onOk = function(e) {
        if (!can_bet()) {
            layer.alert("已封盘，不能下注！", {
                icon: 2,
                time: 2,
            });
            return;
        }

        var data;
        var f = context.global.game[game].getCounterList;
        if (f) data = f(get_counter_list);
        else data = get_counter_list();
        if (isEmpty(data)) {
            layer.alert("下注内容不正确，请重新下注", {
                icon: 2
            });
            return;
        }

        // 显示确认提示框
        show_bet_confirm_list(data);
    };

    // 重置按钮的处理
    var onReset = function(e) {
        reset_counter();
    };

    if ($(".u-bet-ok").attr("had-register-event") != 1) {
        $(".u-bet-ok").attr("had-register-event", 1);
        $(".u-bet-ok").click(onOk);
        $(".u-bet-reset").click(onReset);
    }
}

// 下注的流程
function do_bet(div) {
    if (!can_bet()) {
        reset_counter();
        alert2("已经封盘，下注失败。", true);
        return;
    }

    // 取得列表
    var data = get_confirm_list(div);

    // 由特定的游戏再解析一把
    var f = context.global.game[game].unpack;
    if (f) data = f(data);
    
    layer.closeAll();
    console.log("下注", "第" + Lottery.curr() + "期", data);
    Lottery.ok(data, Lottery.curr(), "pc");
}

// 取得确认后的列表
function get_confirm_list(div) {
    var data = {};
    var arr = div.find("tbody tr");
    for (var i = 0; i < arr.length; i++) {
        var tr = $(arr[i]);
        var k = tr.attr("value");
        if (!k) continue;
        if (!tr.find("input[type='checkbox']")[0].checked) continue;
        var amount = tr.find(":text").val();
        data[k] = parseInt(amount) * 100;
    }
    return data;
}

// 计算下注的注单数量和总额
function calc_bet_count(div) {
    var count = 0, total = 0;
    var f = context.global.game[game].calcBetList;
    if (f) {
        var arr = f(get_confirm_list(div));
        count = arr[0];
        total = arr[1];
    }
    else {
        // 走统一的流程
        count = 0;
        total = 0;
        var arr = div.find("tbody tr");
        for (var i = 0; i < arr.length; i++) {
            var tr = $(arr[i]);
            var k = tr.attr("value");
            if (!k) continue;
            if (!tr.find("input[type='checkbox']")[0].checked) continue;
            var amount = tr.find(":text").val();
            total += parseInt(amount) * 100;
            count++
        }
    }
    return [count, total];
}

// 显示下注确认提示框
function show_bet_confirm_list(data) {
    var count = 0, total = 0;
    
    // 对数据做下加工(各游戏自行定义)
    if (window.parse_bet_list) {
        data = parse_bet_list(data);
        console.log("加工后的投注", data);
    }

    // 将所有单据填充进来
    var l = '<tr style="height: 30px;" value="__k__">' +			
            '  <td style="text-align: left;padding-left:5px;" class="multiple">__title__</td>' +
            '  <td><span class="c-txt3">__rate__</span></td>' +
            '  <td><input type="text" style="width: 85%" value="__v__"></td>' +
            '  <td><input type="checkbox" checked="checked"></td>' +
            '</tr>';
    var p = "";
    for (var k in data) {
        // 取得赔率
        var key = k;
        if (key.indexOf(":") > -1)
            key = key.split(":")[0];
        var rate = gameRule.map[key] ? gameRule.map[key].rate : "";

        // 取得显示的名称
        var name = gameRule.getTargetName(k);
        var f = context.global.game[game].parseTarget;
        if (f)
            name = f(k);

        var l2 = l.replace(/__k__/, k);
        l2 = l2.replace(/__title__/, name);
        l2 = l2.replace(/__rate__/, rate);
        l2 = l2.replace(/__v__/, parseInt(data[k]/100));
        p += l2;
    }
    var div = $("#win_bet");
    div.find("table").find("tbody").html(p);

    // 计算组数与总额的回调处理
    var cb = function() {
        var r = calc_bet_count(div);
        count = r[0];
        total = r[1];
        div.find(".bcountVal").html(count);
        div.find(".btotalVal").html(parseInt(total/100).toFixed(2));
    };
    cb();

    var height = "";
    if (count > 10) height = "420px";
    var layerIndex = layer.open({
        skin: 'demo-class',
        title: "下注明细（请确认注单）",
        type: 1,
        shift: 2,
        area: ["460px", height],
        shadeClose: false,
        btn: ["确定", "取消"],
        content: div,
        zIndex: 5,
        yes: function() {
            do_bet(div);
        },
        cancel: function() {
            layer.confirm("你确定取消下注吗？", {
                icon: 3,
                title: "用户提示",
                zIndex: 6
            }, function() {
                layer.closeAll();
                reset_counter();
            });
            return false;
        },
        end: function() {
            div.find("tbody").empty();
        },
        success: function() {
            div.find(":text").blur(function() {
                cb();
            });
            div.find(":checked").change(function() {
                cb();
            });
        }
    });
}

// 选中某个下注项
function counter_select(k, container) {
    var counter = $("#bet_money1").val();
    var l = 'td[value="__v__"]'.replace(/__v__/, k);
    container.find(l).addClass("bg_yellow");
    container.find(l + ' input').val(counter);
}

// 取消某个下注项
function counter_cancel(k, container) {
    var l = 'td[value="__v__"]'.replace(/__v__/, k);
    container.find(l).removeClass("bg_yellow");
    container.find(l + ' input').val('');
}

// 扫描所有的下注项，并关注其选中
function scan_bet_items() {
    var onClick = function(e) {
        if (!_enableBet) {
            alert2("游戏暂时禁止下注！", true);
            return;
        }

        if (!can_bet()) return;

        var item = $(e.currentTarget);
        var targetItem = item.attr("value");
        if (!targetItem) return;

        var counter = $("#bet_money1").val();
        if (item.attr("class").indexOf("bg_yellow") != -1) {
            counter_cancel(targetItem, item.parent());
            return;
        }
        counter_select(targetItem, item.parent());
    };

    var tab = "#tab" + $("#cate_menus_50 .selected").attr("tid");
    $(tab + " table.u-table2 td").click(onClick);

    $(tab + " table.u-table2 td").on({
        mouseover: function(e) {
            var item = $(e.currentTarget);
            if (item.attr("class") && item.attr("class").indexOf("bg_yellow") != -1) return;
            var targetItem = item.attr("value");
            if (!targetItem) return;
            $('td[value="' + targetItem + '"]').addClass("hover");
        },
        mouseout: function(e) {
            var item = $(e.currentTarget);
            if (item.attr("class") && item.attr("class").indexOf("bg_yellow") != -1) return;
            var targetItem = item.attr("value");
            if (!targetItem) return;
            $('td[value="' + targetItem + '"]').removeClass("hover");
        },
    });
    $(tab + " table.u-table2 td input[name='counter-input']").click(function(e) {
        // 直接选中
        var item = $(e.currentTarget).parent();
        var targetItem = item.attr("value");
        if (!targetItem) return;

        counter_select(targetItem, item.parent());
        e.stopPropagation();
    });
}

// 取得所有已选中的投注框
function get_selected_inputs() {
    var i = $(".cate_menu a.selected").attr("tid");
    
    var arr = $("#tab" + i + " td.bg_yellow input[name='counter-input']");
    var list = [];
    for (var i = 0; i < arr.length; i++)
        list.push($(arr[i]));
    return list;
}

// 取得投注列表
function get_counter_list() {
    var i = $(".cate_menu a.selected").attr("tid");
    var data = {};
    var arr = $("#tab" + i + " td.bg_yellow input[name='counter-input']");
    for (var i = 0; i < arr.length; i++) {
        var amount = $(arr[i]).val().trim();
        if (amount == '') continue;
        amount = parseInt(amount);
        if (amount < 1) continue;

        // 最终以分为单位
        data[$(arr[i]).parent().attr("value")] = amount * 100;
    }
    return data;
}

// 重置所有数据
function reset_counter() {
    var f = function() {
        $("td.bg_yellow").removeClass("bg_yellow");
        $("td.hover").removeClass("hover");

        if (!fengpan)
            $("input[name='counter-input']").val("");
    };
    var cb = context.global.game[game].reset;
    if (cb) cb(f);
    else f();
}

// 机器人，自动投注
function auto_bet_debug() {
    // 取得投注列表
    var f = function() {
        if (!can_bet()) return;
        var i = $(".cate_menu a.selected").attr("tid");
        var data = {};
        var arr = $("input[name='counter-input']");
        var index = Math.round(Math.random() * arr.length);
        if (index > arr.length - 1) index = arr.length - 1;
        var target = $(arr[index]).parent().attr("value");
        if (!target) return;
        var amount = parseInt(100 * Math.random()) + 1;
        
        data[target] = amount * 100;
        Lottery.ok(data, Lottery.curr(), "pc");
    }
    setInterval(function() {
        f();
    }, 4000);
}
